package yueyong.salarymanagement.util;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import org.apache.commons.lang3.tuple.Pair;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.util.EntityUtils;
import sun.misc.BASE64Encoder;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.TreeMap;

/**
 * Copyright: yueyong (c) 2022
 *
 * @author he.shaorong
 * @version 1.0
 * @date 2022/3/9
 */
public class SendEmailUtilV2 {
    public static final String TIMESTAMP = "https://api.mysubmail.com/service/timestamp";
    private static final String URL = "https://api.mysubmail.com/mail/send";
    public static final String TYPE_MD5 = "md5";
    public static final String TYPE_SHA1 = "sha1";
    public static final String FROM_EMAIL_NAME = "悦用工资条";
    public static final String SUBJECT_NAME = "您的当月工资条";
    public static final String FROM_DOMAIN_EMAIL = "yueyong.tech@service.yyysmart.com";
    public static final String APPID = "17159";
    public static final String APPKEY = "800327f7af0fba74544209fe074405ca";

    public static Pair<Boolean, String> sendEmail(String content, String targetEmailAddress) {
        TreeMap<String, String> requestData = new TreeMap<String, String>();
        String appid = APPID;
        String appkey = APPKEY;
        String to = targetEmailAddress;
        String from = FROM_DOMAIN_EMAIL;
        String from_name = FROM_EMAIL_NAME;
        String reply = "";
        String cc = "";
        String bcc = "";
        String subject = SUBJECT_NAME;
        String text = "";
        String html = content;
        JSONObject vars = new JSONObject();
        vars.put("param1", "3334");
        vars.put("param2", "张三丰");
        JSONObject links = new JSONObject();
        links.put("l1", "xxxx");
        links.put("l2", "xxxx");


        String headers = "";
        String asynchronous = "true";
        String tag = "xxxx";
        String sign_type = "md5";
        String sign_version = "2";
        //组合请求数据
        requestData.put("appid", appid);
        requestData.put("to", to);
        requestData.put("from", from);
        requestData.put("from_name", from_name);
        requestData.put("subject", subject);
        requestData.put("tag",tag);


        if (sign_type.equals(TYPE_MD5) || sign_type.equals(TYPE_SHA1)) {
            String timestamp = getTimestamp();
            requestData.put("timestamp", timestamp);
            requestData.put("sign_type", sign_type);
            requestData.put("sign_version", sign_version);
            String signStr = appid + appkey + RequestEncoder.formatRequest(requestData) + appid + appkey;
            System.out.println(signStr);
            requestData.put("signature", RequestEncoder.encode(sign_type, signStr));
        } else {
            requestData.put("signature", appkey);
        }
        //sign_version=2 这些参数不参与signature参数加密计算
        requestData.put("cc",cc);
        requestData.put("bcc",bcc);
        requestData.put("headers",headers);
        requestData.put("text", text);
        requestData.put("html", html);
        requestData.put("vars", vars.toJSONString());
        requestData.put("links", links.toJSONString());

        System.out.println("requestData = " + requestData);
        //post请求
        HttpPost httpPost = new HttpPost(URL);
        httpPost.setHeader("Accept", "application/json");
        httpPost.setHeader("Content-Type", "application/json");
        StringEntity entity = new StringEntity(JSONObject.toJSONString(requestData), "UTF-8");
        httpPost.setEntity(entity);
        try {
            CloseableHttpClient closeableHttpClient = HttpClientBuilder.create().build();
            HttpResponse response = closeableHttpClient.execute(httpPost);
            HttpEntity httpEntity = response.getEntity();
            if (httpEntity != null) {
                String jsonStr = EntityUtils.toString(httpEntity, "UTF-8");
                System.out.println("Send email result:" + jsonStr);
                //解析错误码
                if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
                    Pair.of(true, response.toString());
                } else {
                    Pair.of(false, "ok");
                }
            }
        } catch (ClientProtocolException e) {
            return Pair.of(false, e.getMessage());
        } catch (IOException e) {
            return Pair.of(false, e.getMessage());
        }
        return Pair.of(true, "ok");
    }

    //获取时间戳
    private static String getTimestamp() {
        CloseableHttpClient closeableHttpClient = HttpClientBuilder.create().build();
        HttpGet httpget = new HttpGet(TIMESTAMP);
        try {
            HttpResponse response = closeableHttpClient.execute(httpget);
            HttpEntity httpEntity = response.getEntity();
            String jsonStr = EntityUtils.toString(httpEntity, "UTF-8");
            if (jsonStr != null) {
                JSONObject json = JSONObject.parseObject(jsonStr);
                return json.getString("timestamp");
            }
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }
}


class Atta {
    private JSONArray jsonArray = new JSONArray();

    public void add(String name, String path) throws Exception {
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("name", name);
        jsonObject.put("data", encodeBase64File(path));
        jsonArray.add(jsonObject);
    }

    public String encodeBase64File(String path) throws Exception {
        File file = new File(path);
        FileInputStream inputFile = new FileInputStream(file);
        byte[] buffer = new byte[(int) file.length()];
        inputFile.read(buffer);
        inputFile.close();
        return new BASE64Encoder().encode(buffer).replaceAll("\n", "");
    }

    public String toJSONString() {
        return jsonArray.toJSONString();
    }
}
